from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ReadOnlyModelViewSet

from .models import Area

from .serializers import AreaSerializer,SubAreaSerializer

from rest_framework_extensions.cache.mixins import CacheResponseMixin

from rest_framework_extensions.cache import mixins

from rest_framework.viewsets import GenericViewSet

from .serializers import AddressSerializer

from rest_framework.response import Response

class AreaViewSet(ReadOnlyModelViewSet,CacheResponseMixin):
    # 行政区划信息
    # 区划信息不分页
    pagination_class = None

    def get_queryset(self):
        #提供数据集
        if self.action=='list':
            return Area.objects.all()
        else:
            return Area.objects.all()

    def get_serializer_class(self):
    #     提供序列化器
        if self.action=='list':
            return AreaSerializer
        else:
            return SubAreaSerializer

class AddressViewSet(mixins.ListCacheResponseMixin.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    # 制定序列化器
    serializer_class = AddressSerializer
    # 增加用户权限
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)
    def create(self,request,*args,**kwargs):
        count=request.user.addresses.count()
        if count>=20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)
        return super().create(request,*args,**kwargs)



    def list(self,request,*args,**kwargs):

        queryset=self.get_queryset()

        serializer=self.get_serializer(queryset,many=True)

        user=self.request.user

        return Response({
            'user_id':user.id,
            'default_address_id':user.default_address_id,
            'limit':20,
            'addresses':serializer.data,

        })
    # 删除地址
    def destroy(self,request,*args,**kwargs):

        address=self.get_object()
        # 进行逻辑删除
        address.is_deleted=True

        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)


from rest_framework.decorators import action

from .serializers import AddressTitleSerializer

    @action(methods=['put'],detail=True)
    def title(self,request,pk=None,address_id=None):
        # 修改标题
        address=self.get_object()
        serializer=AddressTitleSerializer(instance=address,data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'],detail=True)
    def status(self,request,pk=None,address_id=None):
        # 设置默认地址
        address=self.get_object()
        request.user.default_address=address
        request.user.save()
        return Response({'message':'OK'},status=status.HTTP_200_OK)

